// pages/game/gameIndex/gameIndex.js、
const app = getApp()


//微信小程序新录音接口，录出来的是aac或者mp3，这里要录成mp3
const mp3Recorder = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const mp3RecoderOptions = {
  duration: 600000,
  sampleRate: 44100,
  numberOfChannels: 1,
  encodeBitRate: 64000,
  format: 'mp3',
  // frameSize: 50
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: null, //获取个人数据
    activeNumber: 0, //头部第一个大标题切换
    show: false, // 展示用户技能弹出
    showCenter: false, //呼叫中心
    gameList: [], //游戏列表
    peopleList: [], //达人推荐列表
    skillActive: -1, //用户单独的的弹出技能列表激活下标
    skillList: [], //用户单独的的技能列表
    status: 0, //1  游戏中 0  可下单
    stepper: 1, //陪练次数
    infoId: null, //点击一个用户技能的infoId
    total: null, //是	int	订单总价
    oneGoodsMoney: null, //单个点击的钱
    gameActive: null, //游戏列表激活
    token: wx.getStorageSync('token'),
    userId: wx.getStorageSync('userId'),
    HuJiaoCenter: [], //呼叫中心
    showCreateRoom: false, //新建房间对话框
    createObj: {
      roomName: '', //	否	string	房间名，非必填参数，如果不携带，会生成默认的房间名。
    },

    roomRange: [], //派单中心的房间列表
  },
  // 获取房间广场接口
  getRoom() {
    var postObj = {
      url: '/room/range/get/roomPark',
      method: 'POST',
      data: {
        roomType: "voice",
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('获取房间广场接口', res.data.data.roomRange);
      var roomRange = res.data.data.roomRange
      if (roomRange.length > 0) {
        roomRange.forEach((items, i) => {
          items.color = app.util.getColor()
        })
      }
      this.setData({
        roomRange: roomRange
      })
    }).catch(err => {

    })
  },
  //监听新增房间数值变化
  onChangeNew(e) {
    // console.log(e.detail);
    const name = e.currentTarget.dataset.name
    const data = `createObj.${name}`
    // console.log(data);
    this.setData({
      [data]: e.detail
    })
  },
  // 确认新建房间
  confirmCreateRoom() {
    let that = this

    if (!!this.data.createObj.roomName) {
      var postObj = {
        url: '/room/join/manager',
        method: 'POST',
        data: {
          token: wx.getStorageSync('token'),
          userId: wx.getStorageSync('userId'),
          roomType: 'voice',
          roomName: this.data.createObj.roomName,
          longitude: wx.getStorageSync('longitude'), // 是 string 经度
          latitude: wx.getStorageSync('latitude'), // 是 string 纬度
          city: !!this.data.info.province ? this.data.info.province : ""
        }
      }
      app.request.noLoginRequest(postObj).then(res => {
        console.log('主持人进入直播间', res.data.data);
        this.closeCreateRoom()
        wx.setStorageSync('voiceRoom', res.data.data)
        // console.log('主持人进入直播间', res)
        wx.navigateTo({
          url: '/pages/game/voiceRoom/voiceRoom',
        })
      }).catch(err => {
        console.log('主持人进入直播间', err)
        wx.showToast({
          title: err.data.desc,
          icon: 'none'
        })
      })

    } else {
      wx.showToast({
        title: '值不可为空',
        icon: 'none'
      })
    }


  },
  // 个人中心页面，获取个人数据
  getInfo() {
    console.log('获取个人数据111')
    var postObj = {
      url: '/user/info/get',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        // telephone: ''
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('获取个人数据', res)
      // console.log(res.data.data)
      this.setData({
        info: res.data.data
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  // 取消或关闭新建房间
  closeCreateRoom() {
    this.setData({
      createObj: {
        roomName: '', //	否	string	房间名，非必填参数，如果不携带，会生成默认的房间名。
      },
      showCreateRoom: false
    })
  },
  // 新建房间
  showCreateRoom() {
    if (!!wx.getStorageSync('token') && !!wx.getStorageSync('userId')) {
      this.setData({
        showCreateRoom: true
      })
    } else {
      wx.navigateTo({
        url: '/pages/index/index',
      })
    }

  },
  // 陪玩者申请提前结束
  applicationClosedEarly(e) {
    let that = this
    console.log(e);
    var data = e.currentTarget.dataset.data
    var orderId = data.orderId
    var infoId = data.infoId
    // 校验订单状态
    var postObj = {
      url: '/manage/client/order/orderStatus',
      method: 'POST',
      data: {
        orderId: orderId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('查询该订单状态', res)
      var status = res.data.data.status
      if (status === 1001) {
        console.log('订单可以使用');
        // 陪玩用户申请提前结束订单
        let postObj = {
          url: '/manage/client/order/applicationClosedEarly',
          method: 'PUT',
          data: {
            orderId: orderId,
            infoId: infoId,
            token: wx.getStorageSync('token'),
            userId: wx.getStorageSync('userId'),
          }
        }
        app.request.gameRequest(postObj).then(res => {
          console.log('陪玩用户申请提前结束订单', res)
          wx.showToast({
            title: '已请求申请结束！',
            icon: 'none',
            duration: 2000,
          })
        }).catch(err => {
          wx.showToast({
            title: '申请失败',
            icon: 'none',
            duration: 2000,
          })
        })

      } else {
        console.log('订单不可以用');
        wx.showToast({
          title: '订单已失效！',
          icon: 'none',
          duration: 2000,
        })
      }
    }).catch(err => {})
  },
  // 用户下单
  orderAdd() {
    let that = this
    var postObj = {
      url: '/manage/client/order/add',
      method: 'POST',
      data: {
        userId: wx.getStorageSync('userId'), //	是	string	用户名
        infoId: this.data.infoId, //	是	string	游戏陪玩ID
        count: this.data.stepper, //	是	string	数量
        total: Number(this.data.total), //	是	int	订单总价
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('用户下单', res)
      wx.showToast({
        title: '邀请成功',
        icon: "success",
        mask: true,
        success: () => {
          var data = res.data.data
          // imgUrl: "https://ywpd-picture.obs.cn-east-2.myhuaweicloud.com:443/photo/838804127-1_photo.png?AccessKeyId=TEPZ5RHAPORK7NWI4AI9&Expires=1697780726&Signature=MxHjVis2VhFWnjr%2FmuWJ41DP6vU%3D"
          // pushUrl: "rtmp://pili-publish.52yuze.com/ywpd/1603704335029"
          // creatTime: "2020-10-26 17:25:35"
          // orderId: 91
          // pullUrl1: "rtmp://pili-live-rtmp.52yuze.com/ywpd/1603704335030"
          // pushUrl1: "rtmp://pili-publish.52yuze.com/ywpd/1603704335030"
          // roomId: 1603704335029
          // roomName: "开黑语音"
          // pullUrl: "rtmp://pili-live-rtmp.52yuze.com/ywpd/1603704335029"




          wx.setStorageSync('voice', data)

          wx.navigateTo({
            url: `/pages/room/room?from=1`,
          })


          that.onClose()
        }
      })

    }).catch(err => {})
  },
  playRecord(e) {
    // console.log(voice);
    var item = e.currentTarget.dataset.item
    var voice = item.voice
    //播放声音文件  
    // wx.playVoice({
    //   filePath: this.data.voice
    // })
    console.log(voice);
    innerAudioContext.src = voice
    innerAudioContext.play()

    innerAudioContext.onPlay(() => {
      console.log('录音播放中');
    })

    innerAudioContext.onStop(() => {
      console.log('录音播放停止');
    })

    innerAudioContext.onEnded(() => {
      console.log('录音播放结束');
    })
  },
  // 获取陪玩者的所有陪玩游戏列表
  getOneGameList(userId) {
    var getObj = {
      // url: '/manage/client/info/list',
      url: '/manage/client/info/lists',
      method: 'GET',
      data: {
        userId: userId,
        status: 1
      }
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('获取陪玩者的所有陪玩游戏列表', res)
      var skillList = res.data.data.data
      var status = res.data.data.status //1  游戏中 0  可下单
      this.setData({
        skillList: skillList,
        status: status
      })

    }).catch(err => {})
  },
  // 查询个人陪玩信息
  getGameList(gameId) {
    var getObj = {
      url: '/manage/client/info/list',
      method: 'GET',
      data: {
        gameId: gameId,
      }
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('查询个人陪玩信息', res)
      var peopleList = res.data.data.list
      this.setData({
        peopleList: peopleList
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  //监听  技能列表 
  onChangeActive(event) {
    console.log(event.detail.name)
    this.setData({
      gameActive: event.detail.name
    })
    this.getGameList(event.detail.name)
  },
  // 技能列表
  getSkillList() {
    var postObj = {
      url: '/manage/client/game/list',
      method: 'GET',
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('获取技能列表', res)
      var firstGameid = res.data.data.list[0].gameId
      // console.log(res.data.data)
      this.setData({
        gameList: res.data.data.list,
        gameActive: firstGameid
      })

      this.getGameList(firstGameid)

    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  // 点击一个技能
  clickSkill(e) {
    // console.log(e)
    var index = e.currentTarget.dataset.index
    var item = e.currentTarget.dataset.item
    var needCoin = e.currentTarget.dataset.item.gift.needCoin
    console.log('点击一个技能', item)
    this.setData({
      skillActive: index,
      total: needCoin,
      stepper: 1,
      oneGoodsMoney: needCoin,
      infoId: item.infoId
    })
  },
  // 顶部title切换
  activeNumberChange(event) {
    console.log(event.detail.name)
    this.setData({
      activeNumber: event.detail.name
    })

    if (event.detail.name == 0) {
      this.getSkillList()
    } else if (event.detail.name == 1) {
      this.getRoom()
    }
  },
  // 展示用户技能弹出
  showPeople(e) {
    console.log('展示用户技能弹出');


    if (!!wx.getStorageSync('token') && !!wx.getStorageSync('userId')) {
      var item = e.currentTarget.dataset.item
      var userId = item.userId
      // console.log(item);
      this.getOneGameList(userId)
      this.setData({
        show: true,
      })
    } else {
      wx.navigateTo({
        url: '/pages/index/index',
      })
    }


  },
  // 关闭用户技能
  onClose() {
    this.setData({
      show: false,
      showCenter: false,
      skillActive: -1,
      stepper: 1,
      total: null,
      oneGoodsMoney: null,
      skillList: [],
      status: 0, //1  游戏中 0  可下单
      HuJiaoCenter: [], //呼叫中心
    })
  },
  // 监听陪练次数
  onChangeStepper(event) {
    this.setData({
      stepper: Number(event.detail),
      total: Number(this.data.oneGoodsMoney) * Number(event.detail)
    })
  },
  // 打开呼叫中心
  openCenter() {
    this.setData({
      showCenter: true,
    })
    this.getHuJiaoCenter() // 陪玩用户的呼叫中心
  },
  // 陪玩用户的呼叫中心
  getHuJiaoCenter() {
    let that = this
    var postObj = {
      url: '/manage/client/order/orderList',
      method: 'GET',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        pageNum: 1,
        pageSize: 10,
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('陪玩用户的呼叫中心', res)
      that.setData({
        HuJiaoCenter: res.data.data.list
      })

    }).catch(err => {
      // console.log('陪玩用户的呼叫中心', err)
    })
  },
  // 点击派单列表中的一项
  textPaste(e) {
    // console.log(e); ***********************************



    // if (!!wx.getStorageSync('token') && !!wx.getStorageSync('userId')) {
    //   let items = e.currentTarget.dataset.items
    //   let roomId = items.roomId
    //   wx.navigateTo({
    //     url: `/pages/game/voiceRoom/voiceRoom?roomId=${roomId}`,
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/index/index',
    //   })
    // }

    wx.setClipboardData({
      data: app.util.config().appUrl,
      success: function (res) {
        wx.showToast({
          title: 'APP链接已复制!',
          icon: 'none',
          duration: 1000
        })
        setTimeout(() => {
          wx.showToast({
            title: '前往APP体验!',
            icon: 'none',
            duration: 1000
          })
        }, 1000)
      }
    })




  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //onLoad中为录音接口注册两个回调函数，主要是onStop，拿到录音mp3文件的文件名（不用在意文件后辍是.dat还是.mp3，后辍不决定音频格式）
    mp3Recorder.onStart(() => {
      console.log('mp3Recorder.onStart()...')
    })
    mp3Recorder.onStop((res) => {
      console.log('mp3Recorder.onStop() ' + res)
      const {
        tempFilePath
      } = res


      // console.log("that.data.voice",that.data.voice)

      // 上传音频
      wx.uploadFile({
        url: that.data.api, // 仅为示例，非真实的接口地址
        filePath: tempFilePath,
        name: 'file',
        formData: {
          file: tempFilePath
        },
        success(res) {
          console.log('上传完成', res);
          var data = JSON.parse(res.data)
          console.log('data', data)

          that.setData({
            voice: data.data
          })
        },
      });
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getSkillList()
    this.onClose()
    if (!!wx.getStorageSync('token') && !!wx.getStorageSync('userId')) {
      app.imInit.imLogin()
      this.getInfo()
      setTimeout(() => {
        // app.imInit.watchMessage()
      }, 1000)
    }

    this.setData({
      activeNumber: 0,
      token: wx.getStorageSync('token'),
      userId: wx.getStorageSync('userId'),
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.onClose()
    this.closeCreateRoom()
    app.imInit.onMessageReceived()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})